package com.example.uberorganizer;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;

import com.example.uberorganizer.util.SystemUiHider;

import android.app.ActionBar;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TimePicker;

/**
 * An example full-screen activity that shows and hides the system UI (i.e.
 * status bar and navigation/system bar) with user interaction.
 * 
 * @see SystemUiHider
 */
public class UserInterfaceFour extends FragmentActivity {
	/**
	 * Whether or not the system UI should be auto-hidden after
	 * {@link #AUTO_HIDE_DELAY_MILLIS} milliseconds.
	 */
	private static final boolean AUTO_HIDE = true;

	/**
	 * If {@link #AUTO_HIDE} is set, the number of milliseconds to wait after
	 * user interaction before hiding the system UI.
	 */
	private static final int AUTO_HIDE_DELAY_MILLIS = 3000;

	/**
	 * If set, will toggle the system UI visibility upon interaction. Otherwise,
	 * will show the system UI visibility upon interaction.
	 */
	private static final boolean TOGGLE_ON_CLICK = true;

	/**
	 * The flags to pass to {@link SystemUiHider#getInstance}.
	 */
	private static final int HIDER_FLAGS = SystemUiHider.FLAG_HIDE_NAVIGATION;

	/**
	 * The instance of the {@link SystemUiHider} for this activity.
	 */
	private SystemUiHider mSystemUiHider;
	
	public GregorianCalendar month, itemmonth;
	public CalendarAdapterBlack adapter;// adapter instance
	public Handler handler;// for grabbing some event values for showing the dot
	public ArrayList<String> items; // container to store calendar items which
	ArrayList<String> event;
	LinearLayout rLayout;
	ArrayList<String> date;
	ArrayList<String> desc;
	static long millis;
	static int[] myDate = new int[3];
	 private ListView mainListView;  
	 private ArrayAdapter<String> listAdapter;
	 int currentPosition;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		View decorView = getWindow().getDecorView();
		// Hide the status bar.
		int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
		decorView.setSystemUiVisibility(uiOptions);
		// Remember that you should never show the action bar if the
		// status bar is hidden, so hide that too if necessary.
		ActionBar actionBar = getActionBar();
		actionBar.hide();

		setContentView(R.layout.activity_user_interface_four);

		//final View controlsView = findViewById(R.id.fullscreen_content_controls);
		//final View contentView = findViewById(R.id.fullscreen_content);

		// Set up an instance of SystemUiHider to control the system UI for
		// this activity.
//		mSystemUiHider = SystemUiHider.getInstance(this, contentView,
//				HIDER_FLAGS);
//		mSystemUiHider.setup();
//		mSystemUiHider
//				.setOnVisibilityChangeListener(new SystemUiHider.OnVisibilityChangeListener() {
//					// Cached values.
//					int mControlsHeight;
//					int mShortAnimTime;
//
//					@Override
//					@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
//					public void onVisibilityChange(boolean visible) {
//						if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
//							// If the ViewPropertyAnimator API is available
//							// (Honeycomb MR2 and later), use it to animate the
//							// in-layout UI controls at the bottom of the
//							// screen.
//							if (mControlsHeight == 0) {
//								mControlsHeight = controlsView.getHeight();
//							}
//							if (mShortAnimTime == 0) {
//								mShortAnimTime = getResources().getInteger(
//										android.R.integer.config_shortAnimTime);
//							}
//							controlsView
//									.animate()
//									.translationY(visible ? 0 : mControlsHeight)
//									.setDuration(mShortAnimTime);
//						} else {
//							// If the ViewPropertyAnimator APIs aren't
//							// available, simply show or hide the in-layout UI
//							// controls.
//							controlsView.setVisibility(visible ? View.VISIBLE
//									: View.GONE);
//						}
//
//						if (visible && AUTO_HIDE) {
//							// Schedule a hide().
//							delayedHide(AUTO_HIDE_DELAY_MILLIS);
//						}
//					}
//				});

		// Set up the user interaction to manually show or hide the system UI.
//		contentView.setOnClickListener(new View.OnClickListener() {
//			@Override
//			public void onClick(View view) {
//				if (TOGGLE_ON_CLICK) {
//					mSystemUiHider.toggle();
//				} else {
//					mSystemUiHider.show();
//				}
//			}
//		});

		// Upon interacting with UI controls, delay any scheduled hide()
		// operations to prevent the jarring behavior of controls going away
		// while interacting with the UI.
//		findViewById(R.id.dummy_button).setOnTouchListener(
//				mDelayHideTouchListener);
		// ---------
		// KALENDARZ
		// ---------
		
		 mainListView = (ListView) findViewById( R.id.mainListView );   
		rLayout = (LinearLayout) findViewById(R.id.text);
		month = (GregorianCalendar) GregorianCalendar.getInstance();
		itemmonth = (GregorianCalendar) month.clone();

		items = new ArrayList<String>();

		adapter = new CalendarAdapterBlack(this, month);

		GridView gridview = (GridView) findViewById(R.id.gridview);
		gridview.setAdapter(adapter);

		handler = new Handler();
		handler.post(calendarUpdater);

		TextView title = (TextView) findViewById(R.id.title);
		title.setText(android.text.format.DateFormat.format("MMMM yyyy", month));

		// odswiezanie kalendarza na wcisnieciu dla przesuniecia kalendarza o
		// miesiac w tyl
		RelativeLayout previous = (RelativeLayout) findViewById(R.id.previous);
		previous.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				setPreviousMonth();
				refreshCalendar();

			}
		});

		// odswiezanie kalendarza na wcisnieciu dla przesuniecia kalendarza o
		// miesiac w przod
		RelativeLayout next = (RelativeLayout) findViewById(R.id.next);
		next.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				setNextMonth();
				refreshCalendar();

			}
		});

		// Funkcja podpieta do wciskania poszczegolnych dni
		gridview.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView parent, View v, int position,
					long id) {
				currentPosition = position;
				// usuwanie poprzedniego widoku jesli dodane
				if (((LinearLayout) rLayout).getChildCount() > 0) {
					((LinearLayout) rLayout).removeAllViews();
				}
				desc = new ArrayList<String>();
				date = new ArrayList<String>();
				((CalendarAdapter) parent.getAdapter()).setSelected(v);
				String selectedGridDate = CalendarAdapter.dayString
						.get(position);
				String[] separatedTime = selectedGridDate.split("-");
				String gridvalueString = separatedTime[2].replaceFirst("^0*",
						"");// bierzemy ostatnia czesc daty (dni)
				int gridvalue = Integer.parseInt(gridvalueString);
				// nastepny albo poprzedni miesiac jesli wcisniemy dni spoza
				// biezacego miesiaca
				if ((gridvalue > 10) && (position < 8)) {
					setPreviousMonth();
					refreshCalendar();
				} else if ((gridvalue < 7) && (position > 28)) {
					setNextMonth();
					refreshCalendar();
				}
				((CalendarAdapter) parent.getAdapter()).setSelected(v);

				for (int i = 0; i < Utility.startDates.size(); i++) {
					if (Utility.startDates.get(i).equals(selectedGridDate)) {
						desc.add(Utility.nameOfEvent.get(i));
					}
				}

				if (desc.size() > 0) {
					for (int i = 0; i < desc.size(); i++) {
						TextView rowTextView = new TextView(
								UserInterfaceFour.this);

						// set some properties of rowTextView or something
						rowTextView.setText("Event:" + desc.get(i));
						rowTextView.setTextColor(Color.BLACK);

						// add the textview to the linearlayout
						rLayout.addView(rowTextView);

					}
				}

				desc = null;
			}
		});

		// Na dlugim wcisnieciu dnia
		gridview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view,
					int position, long id) {
				currentPosition = position;
				FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
				EventDialog dial = new EventDialog(); // klasa odpowiedzialna za
														// okienko dodawania
														// wydarzen
				((CalendarAdapter) parent.getAdapter()).setSelected(view); // zaznaczamy
																			// dzien
																			// ktory
																			// wcisnelismy
				String selectedGridDate = CalendarAdapter.dayString
						.get(position); // pobieramy biezaca date
				String[] separatedTime = selectedGridDate.split("-"); // rozdzielamy
																		// usuwajac
																		// '-'

				myDate[0] = Integer.parseInt(separatedTime[0]); // rok
				myDate[1] = Integer.parseInt(separatedTime[1]); // miesiac
				myDate[2] = Integer.parseInt(separatedTime[2]); // dzien
				dial.show(ft, "addevent");
				return true;
			}

		});

		// ---------
		// KALENDARZ
		// ---------

	}

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);

		// Trigger the initial hide() shortly after the activity has been
		// created, to briefly hint to the user that UI controls
		// are available.
		//delayedHide(100);
	}

	/**
	 * Touch listener to use for in-layout UI controls to delay hiding the
	 * system UI. This is to prevent the jarring behavior of controls going away
	 * while interacting with activity UI.
	 */
//	View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() {
//		@Override
//		public boolean onTouch(View view, MotionEvent motionEvent) {
//			if (AUTO_HIDE) {
//				delayedHide(AUTO_HIDE_DELAY_MILLIS);
//			}
//			return false;
//		}
//	};
//
//	Handler mHideHandler = new Handler();
//	Runnable mHideRunnable = new Runnable() {
//		@Override
//		public void run() {
//			mSystemUiHider.hide();
//		}
//	};
//
//	/**
//	 * Schedules a call to hide() in [delay] milliseconds, canceling any
//	 * previously scheduled calls.
//	 */
//	private void delayedHide(int delayMillis) {
//		mHideHandler.removeCallbacks(mHideRunnable);
//		mHideHandler.postDelayed(mHideRunnable, delayMillis);
//	}

	// odswiezenie kalendarza
	public void refreshCalendar() {
		TextView title = (TextView) findViewById(R.id.title);

		adapter.refreshDays();
		adapter.notifyDataSetChanged();
		handler.post(calendarUpdater); // generate some calendar items

		title.setText(android.text.format.DateFormat.format("MMMM yyyy", month));
	}

	public Runnable calendarUpdater = new Runnable() {

		@Override
		public void run() {
			items.clear();

			// Print dates of the current week
			DateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
			String itemvalue;
			event = Utility.readCalendarEvent(UserInterfaceFour.this);
			   listAdapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.simplerowwhite,(List<String>)event);  
			   mainListView.setAdapter( listAdapter ); 

			for (int i = 0; i < Utility.startDates.size(); i++) {
				itemvalue = df.format(itemmonth.getTime());
				itemmonth.add(GregorianCalendar.DATE, 1);
				items.add(Utility.startDates.get(i).toString());
			}
			adapter.setItems(items);
			adapter.notifyDataSetChanged();
		}
	};

	// przechodzenie do nastepnego miesiaca
	protected void setNextMonth() {
		if (month.get(GregorianCalendar.MONTH) == month
				.getActualMaximum(GregorianCalendar.MONTH)) {
			month.set((month.get(GregorianCalendar.YEAR) + 1),
					month.getActualMinimum(GregorianCalendar.MONTH), 1);
		} else {
			month.set(GregorianCalendar.MONTH,
					month.get(GregorianCalendar.MONTH) + 1);
		}

	}

	// przechodzenie do poprzedniego miesiaca
	protected void setPreviousMonth() {
		if (month.get(GregorianCalendar.MONTH) == month
				.getActualMinimum(GregorianCalendar.MONTH)) {
			month.set((month.get(GregorianCalendar.YEAR) - 1),
					month.getActualMaximum(GregorianCalendar.MONTH), 1);
		} else {
			month.set(GregorianCalendar.MONTH,
					month.get(GregorianCalendar.MONTH) - 1);
		}

	}

	public void Reload() {
		finish();
		startActivity(getIntent());
	}
	
	public void showEventDialog(View v)
	{
		FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
		EventDialog dial = new EventDialog(); // klasa odpowiedzialna za okienko dodawania wydarzen
		String selectedGridDate = CalendarAdapter.dayString.get(currentPosition);  // pobieramy biezaca date
		String[] separatedTime = selectedGridDate.split("-");  // rozdzielamy usuwajac '-'

	    myDate[0]=Integer.parseInt(separatedTime[0]); // rok
	    myDate[1]=Integer.parseInt(separatedTime[1]); // miesiac
	    myDate[2]=Integer.parseInt(separatedTime[2]); // dzien
		dial.show(ft, "addevent");
	}
	
	public void showTimePickerDialog(View v) {
		TimePickerFragment newFragment = new TimePickerFragment();
	    newFragment.show(getSupportFragmentManager(), "timePicker");
	}
	
	// funkcja do wybierania godziny
	public void showTimePickerDialogEnd(View v) {
		TimePickerFragmentEnd newFragment = new TimePickerFragmentEnd();
	    newFragment.show(getSupportFragmentManager(), "timePicker");
	}
	
	public static class TimePickerFragment extends DialogFragment
    implements TimePickerDialog.OnTimeSetListener 
    {
TextView t;
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) 
{
// Use the current time as the default values for the picker
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);


// Create a new instance of TimePickerDialog and return it
return new TimePickerDialog(getActivity(), this, hour, minute,
		 android.text.format.DateFormat.is24HourFormat(getActivity()));
}

@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
	// na ustawieniu godziny tworzymy pelna date
   Calendar start = Calendar.getInstance();
   start.set(myDate[0], myDate[1]-1,myDate[2], hourOfDay, minute, 0);

   //wstawiamy ja w milisekundach do zmiennej
	EventDialog.startTime = start.getTimeInMillis(); 
	// wypisujemy na naszym okienku dodajacym zdarzenie
	EventDialog.t1.setText(Integer.toString(hourOfDay)+':'+Integer.toString(minute));
	
}
}


public static class TimePickerFragmentEnd extends DialogFragment
implements TimePickerDialog.OnTimeSetListener {

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
//Use the current time as the default values for the picker
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);

//Create a new instance of TimePickerDialog and return it
return new TimePickerDialog(getActivity(), this, hour, minute,
android.text.format.DateFormat.is24HourFormat(getActivity()));
}

@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) 
{
	// na ustawieniu godziny tworzymy pelna date
   Calendar start = Calendar.getInstance();
   start.set(myDate[0], myDate[1],myDate[2], hourOfDay, minute, 0);
 //wstawiamy ja w milisekundach do zmiennej
	EventDialog.endTime = start.getTimeInMillis(); 
	// wypisujemy na naszym okienku dodajacym zdarzenie
EventDialog.t2.setText(Integer.toString(hourOfDay)+':'+Integer.toString(minute));
}
}

}
